﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace KokosSearcher
{
	public partial class AuctionSearchForm : Form
	{
		private KokosData kokosData;

		public AuctionSearchForm()
		{
			InitializeComponent();
		}

		private void btnSzukaj_Click(object sender, EventArgs e)
		{
			this.backgroundWorker.RunWorkerAsync();
		}

		private void txtIdAukcji_KeyPress(object sender, KeyPressEventArgs e)
		{
			if(!char.IsDigit(e.KeyChar))
			{
				this.btnSzukaj.Enabled = false;
			}
			else
			{
				this.btnSzukaj.Enabled = true;
			}
		}

		private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
		{
			BackgroundWorker worker = sender as BackgroundWorker;

			worker.ReportProgress(1);
			
			this.kokosData = new KokosData();
			kokosData.getAuctionData(this.txtIdAukcji.Text);
		}

		private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
		{
			this.toolStripStatusLabel1.Visible = true;
			this.picLoader.Visible = false;

			if (kokosData.Auction != null)
			{
				this.txtUzytkownik.Text = kokosData.Auction.User.User;

				if (String.IsNullOrEmpty(kokosData.Auction.User.User))
				{
					this.btnDodaj.Enabled = false;
					this.toolStripStatusLabel1.Text = "Aukcja w trakcie tworzenia";
				}
				else
				{
					this.toolStripStatusLabel1.Visible = false;
					this.btnDodaj.Enabled = true;
				}
			}
			else
			{
				this.toolStripStatusLabel1.Visible = true;
				this.toolStripStatusLabel1.Text = "Nie znaleziono aukcji o wskazanym Id";
				this.btnDodaj.Enabled = false;
			}
		}

		private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
		{
			this.toolStripStatusLabel1.Visible = true;
			
			if (e.ProgressPercentage == 1)
			{
				this.toolStripStatusLabel1.Text = "Trwa wyszukiwanie aukcji...";
				this.picLoader.Visible = true;
			}
			else
			{
				this.toolStripStatusLabel1.Text = "Nie znaleziono aukcji o wskazanym Id";
				this.picLoader.Visible = false;
			}
		}

		private void btnDodaj_Click(object sender, EventArgs e)
		{
			if (this.kokosData.Auction != null)
			{
				string saveInformation;

				saveInformation = this.kokosData.saveAuctionToDB(this.kokosData.Auction);

				if (String.IsNullOrEmpty(saveInformation))
				{
					this.toolStripStatusLabel1.Text = "Dodano wskazaną aukcję do bazy";
				}
				else
				{
					this.toolStripStatusLabel1.Text = saveInformation;
				}
			}
			else
			{
				this.toolStripStatusLabel1.Text = "Nie udało się dodać aukcji do bazy";
			}
		}
	}
}
